<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;

class WeCommunity extends Common

{
    //缘分广场
    public function getRecommendUserInfo()
    {
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		$data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:12;
        $sort = !empty($data['sort'])?$data['sort']:'Browse_volume';
		$field = "a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,a.Browse_volume,b.Introduce,b.Phone,b.Wechat,b.Realname,b.Card_portrait,b.Card_address,b.Company,b.Occupation,c.Campus,c.Industrys,c.Hobbys,c.Age,c.Demand,c.Languages,c.Gender,c.Marriage,c.Position,c.Longitud,c.Latitude,c.Hometowns,c.Locations";
		if(!$re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$uid))->field($field)->find())
		return json_encode(['code'=>10002,'msg'=>'网络异常']);
		$rb = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.State'=>1))->where('a.User_id','<>',$uid)->field($field)->select();
		$result = $this->_queryPairAllUserList($re,$rb,$sort);
		$start = ($page-1)*$pagesize;
		$arr = array_slice($result, $start, $pagesize);//分页显示
        if($arr)
		return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$arr]);
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    
    }
    //获取用户好友/黑名单
    public function getUserFriendTypeList()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        if(empty($data['ftye']) || !$data['ftye'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $flye = $data['ftye'];
        if($flye == 1){
            $result = getUserFriendInfo($uid,'Friend_ids');
        }elseif($flye == 2){
            $result = getUserFriendInfo($uid,'Blacklist_ids');
        }else{
            return json_encode(['code'=>10002,'msg'=>'参数错误']);
        }
        if(!$result && !in_array($result))
        return json_encode(['code'=>10002,'msg'=>'暂无数据']);
        $ids = implode(',',$result);
        $where['User_id'] = ['in',$ids];
        if(!$arr = Db::name('user_friend')->where($where)->select())
        return json_encode(['code'=>10002,'msg'=>'暂无数据']);
        foreach($arr as $a=>$r){
            $arr['isFirend'] = judgeUserFriend($uid,$r['User_id']);
        }
        return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$arr]);
    }

    //添加好友
     public function getAddUserFriend(){
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        if(empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $mid = json_encode($mid);
        $num = count($mid);
        if(!$re = Db::name('user')->where(array('User_id'=>$uid,'State'=>1))->find())
        return json_encode(['code'=>10002,'msg'=>'暂时无权限执行此操作']);
        $where['User_id'] = ['in',$mid];
        $where['State'] = ['=',1];
        if(!$rb = Db::name('user')->where($where)->field('User_id,Username')->select())
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        foreach($rb as $r => $b){
            if(judgeUserFriend($uid,$b['User_id']))
            return json_encode(['code'=>10002,'msg'=>'用户'.$b['Username'].'已是您的好友，不可重复添加']);
            if(judgeUserBlacklist($uid,$b['User_id']))
            return json_encode(['code'=>10002,'msg'=>'用户'.$b['Username'].'已把你拉黑，已成为你得不到的朋友']);
        }
        $time = time();
        $snum = $re['Add_friends_second']*1+$num;
//        //判断今日是否已分享过
//        if(judgeDiffDays(getdate($re['Share_time']),getdate($time))){//未分享
//            if($snum > 6 && !judgeDiffDays(getdate($re['Add_friends_time']),getdate($time)))
//            return json_encode(['code'=>10002,'msg'=>'普通会员每日只能添加6位好友']);
//        }else{//已分享
//            if($snum > 3 && !judgeDiffDays(getdate($re['Add_friends_time']),getdate($time)))
//            return json_encode(['code'=>10002,'msg'=>'普通会员每日可免费添加3位好友，分享至朋友圈可获得三次交友机会，赶紧来试试吧','data'=>'ok']);
//        }
        $ids = array_column($rb, 'User_id');
        Db::startTrans();
        if(Db::name('user')->where(array('User_id'=>$uid))->update(array('Add_friends_second'=>$snum,'Add_friends_time'=>$time))){
            try{
                if($rc = Db::name('user_friend')->where(array('User_id'=>$uid))->find()){
                    $firs = json_decode($rc['Friend_ids']);
                    $firs = json_encode(array_unique(array_merge($ids, $firs)));
                    Db::name('user_friend')->where(array('User_id'=>$uid))->update(array('Friend_ids'=>$firs));
                }else{
                    $arr = [
                        'Friend_ids' => json_encode($ids),
                        'User_id' => $uid,
                    ];
                    Db::name('user_friend')->insert($arr);
                }
                Db::commit();
                return json_encode(['code'=>10001,'msg'=>'添加好友成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json_encode(['code'=>10002,'msg'=>'网络异常']);
            }
        }
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
     }

     //拉黑好友
     public function getAddUserBlacklist(){
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        if(empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $where['User_id'] = ['in',$mid];
        $where['State'] = ['=',1];
        if(!$re = Db::name('user')->where(array('User_id'=>$uid,'State'=>1))->find())
        return json_encode(['code'=>10002,'msg'=>'暂时无权限执行此操作']);
        if(!$rb = Db::name('user')->where($where)->field('User_id,Username')->select())
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        foreach($rb as $r => $b){
            if(judgeUserBlacklist($uid,$b['User_id']))
            return json_encode(['code'=>10002,'msg'=>'用户'.$b['Username'].'已存在你的黑名单，不可重复操作']);
        }
        if(!$rc = Db::name('user_friend')->where(array('User_id'=>$uid)))
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        $ids = array_column($rb, 'User_id');
        $firs = json_decode($rc['Friend_ids']);
        $blks = json_decode($rc['Blacklist_ids']);
        $firs = json_encode(array_diff($firs,$blks));
        $blks = json_encode(array_unique(array_merge($ids, $blks)));
        if(Db::name('user_friend')->where(array('User_id'=>$uid))->update(array('Blacklist_ids'=>$blks,'Friend_ids'=>$firs)))
        return json_encode(['code'=>10001,'msg'=>'拉黑成功']);
        return json_encode(['code'=>10002,'msg'=>'操作失败']);
     }
     //删除好友
     public function getDeleteUserFriend()
     {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        if(empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $where['User_id'] = ['in',$mid];
        $where['State'] = ['=',1];
        if(!$re = Db::name('user')->where(array('User_id'=>$uid,'State'=>1))->find())
        return json_encode(['code'=>10002,'msg'=>'暂时无权限执行此操作']);
        if(!$rb = Db::name('user')->where($where)->field('User_id,Username')->select())
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        foreach($rb as $r => $b){
            if(!judgeUserFriend($uid,$b['User_id']))
            return json_encode(['code'=>10002,'msg'=>'用户'.$b['Username'].'还不是您的好友，不可执行此操作']);
        }
        if(!$rc = Db::name('user_friend')->where(array('User_id'=>$uid)))
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        $ids = array_column($rb, 'User_id');
        $firs = json_encode(array_diff(json_decode($rc['Friend_ids']),$ids));
        if(Db::name('user_friend')->where(array('User_id'=>$uid))->update(array('Friend_ids'=>$firs)))
        return json_encode(['code'=>10001,'msg'=>'添加好友成功']);
        return json_encode(['code'=>10002,'msg'=>'添加好友失败']);
     }

    //搜索用户信息
    public function getSearchUserList()
    {
        $data = input('post.');
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
		$uid = $data['uid'];
        if(empty($data['key']) || !$data['key'])
        return json_encode(['code'=>10002,'msg'=>'搜索内容不能为空']);
		$page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:12;
		$key = $data['key'];
		$type = !empty($data['type'])?$data['type']:'';
		$field = "a.State,a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,a.Browse_volume,a.Browse_volume,b.Introduce";
		$order = 'Browse_volume desc,Addtime desc';
		$where['a.State'] = ['=',1];
		$where['a.User_id'] = ['<>',$uid];
		if($type == 'user'){
			$where['a.Username'] = ['like','%'.$key.'%'];
			$re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->where($where)->field($field)->order($order)->page($page)->limit($pagesize)->select();
		}else if($type == 'card'){
			$where['b.Introduce'] = ['like','%'.$key.'%'];
			$re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->where($where)->field($field)->order($order)->page($page)->limit($pagesize)->select();
		}else{
			$whereOr['a.Username'] = ['like','%'.$key.'%'];
			$whereOr['b.Introduce'] = ['like','%'.$key.'%'];
			$re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->where($where)->whereOr($whereOr)->order($order)->field($field)->page($page)->limit($pagesize)->select();
		}
		if($re){
			foreach($re as $r=>$e){
				$re[$r]['Giveup_volume'] = count(getUserGiveUpList($e['User_id']));
				$re[$r]['format_addtime'] = getFormatTime($e['Addtime']);
			}
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
		}
        return json_encode(['code'=>10001,'msg'=>'没有更多了']);
    }


    //获取个人基本信息
    public function getBrowsePersonalUserBasic(){
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $where['User_id'] = ['=',$uid];
        $field = 'Head_portrait,Addtime,State,Username,Smallchange,Cash_time,Cash_amount,User_id';
        if($re = Db::name('user')->where($where)->field($field)->find()){
            $re['Integrity'] = judgeUserCardInfo($uid);
            $re['Card_portrait'] = getUserCardInfo($uid,'Card_portrait');
            $re['Issue_Amt'] = round(getRedenvelopesSum($uid),2);
            $re['Issue_Nums'] = getRedenvelopesUserCount($uid);
			$re['Collect_Amt'] = round(getRedenvelopesCodeSum($uid),2);
			$re['Collect_Nums'] = getRedenvelopesCodeUserCount($uid);
		}
        $re['isShow'] = false;//控制小程序按钮显示fasle隐藏true显示
        return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$re]);
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
        
    }

     //获取个人名片信息
    public function getBrowsePersonalUserCardInfo()
    {
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $field = "a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,a.Browse_volume,b.Introduce,b.Phone,b.Wechat,b.Realname,b.Card_portrait,b.Card_address,b.Company,b.Occupation";
        if($re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$uid))->Field($field)->find()){
            // $re['Poster'] = getUserPosterInfo($uid);//获取海报
            $re['format_addtime'] = getFormatTime($re['Addtime']);
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'网络异常']);
    }

    //浏览个人信息
    public function getBrowsePersonalUserInfo()
    {
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $field = "a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,a.Browse_volume,b.Introduce,b.Phone,b.Wechat,b.Realname,b.Card_portrait,b.Card_address,b.Company,b.Occupation,c.Campus,c.Industrys,c.Hobbys,c.Age,c.Demand,c.Languages,c.Gender,c.Marriage,c.Position,c.Longitud,c.Latitude,c.Hometowns,c.Locations";
        if($re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$uid))->Field($field)->find()){
            // $re['Poster'] = getUserPosterInfo($uid);//获取海报
            $re['format_addtime'] = getFormatTime($re['Addtime']);
            $re['Giveup_volume'] = count(getUserGiveUpList($uid));
            // //查询被领红包记录
            // if($ids = getUserRedenvelopesCodeList($uid)){
            //     $result = gteCountRedenvelopesCodeSingle($ids);
            //     $re['RedbagCodeList']  = $result['list'];
            //     $re['RedbagCodeCount']  = $result['count'];
            // }
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'暂无数据']);
    }


    //浏览TA人信息
    public function getBrowseOtherUserInfo()
    {
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];  
        $mid = $data['mid'];  
        $field = "a.Username,a.User_id,a.Head_portrait,a.Land_time,a.Addtime,a.Browse_volume,b.Introduce,b.Phone,b.Wechat,b.Realname,b.Card_portrait,b.Card_address,b.Company,b.Occupation,c.Campus,c.Industrys,c.Hobbys,c.Age,c.Demand,c.Languages,c.Gender,c.Marriage,c.Position,c.Longitud,c.Latitude,c.Hometowns,c.Locations";
        if($re = Db::name('user')->alias('a')->join('user_card b','a.User_id = b.User_id','LEFT')->join('user_fate_gene c','a.User_id = c.User_id','LEFT')->where(array('a.User_id'=>$mid))->Field($field)->find()){
            //$re['Poster'] = getUserPosterInfo($mid);//获取海报
            $re['format_addtime'] = getFormatTime($re['Addtime']);   
            $re['Giveup_volume'] = count(getUserGiveUpList($mid));
			$re['Giveup_state'] = judgeUserGiveUpState($uid,$mid);        
            // //查询被领红包记录
            // if($ids = getUserRedenvelopesCodeList($mid)){
            //     $result = gteCountRedenvelopesCodeSingle($ids);
            //     $re['RedbagCodeList']  = $result['list'];
            //     $re['RedbagCodeCount']  = $result['count'];
            // }
            $re['Fate'] = getMatchingMarginValue($uid,$mid);//检测缘分值
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'暂无数据','data'=>$data]);
    }

    //获取用户海报
    public function getUserAllPoster()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $mid = $data['mid'];
        $data = getUserPosterInfo($mid);
        return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$data]);
    }

    //查询用户是否存在新消息或未读消息
    public function getNewMessageReply()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $arr = [
            'NewMsg'=>judgeUserNewMessage($uid),
            'NewReply'=>judgeUserNewReply($uid),
        ];
       return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$arr]);
    }
    //新增留言
    public function getAddMessage()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        if(empty($data['content']) || !$data['content'])
        return json_encode(['code'=>10002,'msg'=>'内容不能为空']);
        $time = time();
        $val = !empty($data['dtype'])?$data['dtype']:'message';
        $arr = [
            'User_id'=>$data['uid'],
            'Giv_user_id'=>$data['mid'],
            'Content'=>$data['content'],
            'State'=>3,
            'Addtime'=>$time,
            'Pid'=>0,
        ];
        if(Db::name($val)->insert($arr))
        return json_encode(['code'=>10001,'msg'=>'留言成功']);
        return json_encode(['code'=>10002,'msg'=>'留言失败']);
    }

    //回复留言
    public function getAddMessageCode()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'] || empty($data['msid']) || !$data['msid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        if(empty($data['content']) || !$data['content'])
        return json_encode(['code'=>10002,'msg'=>'内容不能为空']);
        $uid = $data['uid'];
        $mid = $data['mid'];
        $msid = $data['msid'];
        $msg = $data['content'];
        $time = time();
        $val = !empty($data['dtype'])?$data['dtype']:'message';
        Db::name($val)->where(array('id'=>$msid))->setField('State',1);
        $arr = [
            'User_id'=>$uid,
            'Giv_user_id'=>$mid,
            'Content'=>$msg,
            'State'=>3,
            'Addtime'=>$time,
            'Pid'=>$msid,
        ];
        if(Db::name($val)->insert($arr))
        return json_encode(['code'=>10001,'msg'=>'回复成功']);
        return json_encode(['code'=>10002,'msg'=>'回复失败']);
    }

    //获取留言版（包括回复）
    public function getMessageAllCodeList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];  
        $type = !empty($data['type'])?$data['type']:'';
        $order = 'Addtime desc';
        $val = !empty($data['dtype'])?$data['dtype']:'message';
        if($type == 1){//我发出的留言
            $where['User_id'] = ['=',$uid];
            $re = Db::name($val)->where($where)->order($order)->select();
        }elseif($type == 2){//我收到的留言
            $where['Giv_user_id'] = ['=',$uid];
            $re = Db::name($val)->where($where)->select();
        }else{//我发出和我收到的
            $whereor['User_id'] = ['=',$uid];
            $whereor['Giv_user_id'] = ['=',$uid];
            $re = Db::name($val)->whereOr($whereor)->order($order)->select();
        }
        if($re){
            $arr = getCommunityReplyInfinite($re);
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    }
    
      
    //获取留言版（不包括回复）
    public function getMessageAllList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];  
        $type = !empty($data['type'])?$data['type']:'';
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:99999;
        $where['Pid'] = ['=',0];
        $where['State'] = ['<>',2];
        $order = 'State desc,Addtime desc';
        $val = !empty($data['dtype'])?$data['dtype']:'message';
        if($type == 1){//我发出的留言
            $where['User_id'] = ['=',$uid];
            $re = Db::name($val)->where($where)->order($order)->page($page)->limit($pagesize)->select();
        }elseif($type == 2){//我收到的留言
            $where['Giv_user_id'] = ['=',$uid];
            $re = Db::name($val)->where($where)->order($order)->page($page)->limit($pagesize)->select();
        }else{//我发出和我收到的
            $whereor['User_id'] = ['=',$uid];
            $whereor['Giv_user_id'] = ['=',$uid];
            $re = Db::name($val)->where($where)->whereOr($whereor)->order($order)->page($page)->limit($pagesize)->select();
        }
        if($re){
            foreach($re as $r=>$e){
                $uf = getUserInfo($e['User_id'],'');
                $mf = getUserInfo($e['Giv_user_id'],'');
                $re[$r]['format_addtime'] = getFormatTime($e['Addtime']);
                $re[$r]['Username'] = $uf['Username'];
                $re[$r]['It_username'] = $mf['Username'];
                $re[$r]['It_head_portrait'] = $mf['Head_portrait'];
                $re[$r]['Head_portrait'] = $uf['Head_portrait'];
                $when['State'] = ['=',3];
                $when['User_id'] = ['<>',$uid];
                $order = 'Addtime desc';
                $ary = array();
                $Reply = getCommunityReplyList($e['id'],$val,$ary,1,$when,$order);
				$ids = '';
				if($Reply && is_array($Reply)){
					$new = array();
					foreach ($Reply as $v){
						$new[]=$v['id'];
					}
					$ids = join(',',$new);
				};
				$re[$r]['Newid'] = $ids;
                $re[$r]['Reply_num'] = count($Reply);
            }
            $sort = 'Reply_num';
            array_multisort(array_column($re,$sort),SORT_DESC,$re);
            return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    }


    //获取单条留言内容详情
    public function getOneMessageLet()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['msid']) || !$data['msid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];  
        $msid = $data['msid'];  
        // $where['User_id'] = ['=',$uid];
        $where['id'] = ['=',$msid];
        if($re = Db::name('message')->where($where)->find()){
            $re['Username'] = getUserInfo($re['User_id'],'Username');
            $re['Head_portrait'] = getUserInfo($re['User_id'],'Head_portrait');
            $re['Vistername'] = getUserInfo($re['Giv_user_id'],'Username');
            $re['format_addtime'] = getFormatTime($re['Addtime']);
            return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'暂无数据']);
    }

    //获取留言回复列表
    public function getMessageCodeList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['msid']) || !$data['msid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:99999;
        $msid = $data['msid'];
        $where['State'] = ['<>',2];
        $order = 'Addtime desc';
        $ary = array();
        $val = !empty($data['dtype'])?$data['dtype']:'message';
        if($arr = getCommunityReplyList($msid,$val,$ary,1,$where,$order,$page,$pagesize)){
            foreach($arr as $a => $r){
                $arr[$a]['Username'] = getUserInfo($r['User_id'],'Username');
                $arr[$a]['Vistername'] = getUserInfo($r['Giv_user_id'],'Username');
                $arr[$a]['format_addtime'] = $r['Addtime'];
            }
            // $arr = getMessageTree($arr);
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    }


	public function getChangeMessageState()
	{
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['nids']) || !$data['nids'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
		$uid = $data['uid'];
		$nids = $data['nids'];
		$val = !empty($data['dtype'])?$data['dtype']:'message';
		$where['id'] = ['in',$nids];
		if(Db::name($val)->where($where)->setField('State',1))
		return json_encode(['code'=>10001,'msg'=>'更新成功']);
		return json_encode(['code'=>10002,'msg'=>'更新失败']);
	}

    //点赞接口
    public function getAddGiveUpNum()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $val = !empty($data['dtype'])?$data['dtype']:'giveup_user';
        $time = time();
        $arr = [
            'User_id'=>$data['uid'],
            'Giv_user_id'=>$data['mid'],
        ];
        if(Db::name($val)->where($arr)->find())
        return json_encode(['code'=>10002,'msg'=>'您已经为Ta点过赞过了']);
        $arr['Addtime'] = time();
        if(Db::name($val)->insert($arr))
        return json_encode(['code'=>10001,'msg'=>'点赞成功']);
        return json_encode(['code'=>10002,'msg'=>'点赞失败']);
    }

    //取消点赞接口
    public function getDellGiveUpNum()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $val = !empty($data['dtype'])?$data['dtype']:'giveup_user';
        $arr = [
            'User_id'=>$data['uid'],
            'Giv_user_id'=>$data['mid'],
        ];
        if(Db::name($val)->where($arr)->delete())
        return json_encode(['code'=>10001,'msg'=>'操作成功']);
        return json_encode(['code'=>10002,'msg'=>'操作失败']);
    }

    //添加用户热点
    public function getAddBrowseNum()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $mid = $data['mid'];  
        $hid = cache('we_user_hot');
        if($hid && $hid == $mid)
        return json_encode(['code'=>10002,'msg'=>'热点记录频繁','data'=>$hid]);
        $where['User_id'] = ['=',$mid];
        if(Db::name('user')->where($where)->Inc('Browse_volume',1)->update())
        cache('we_user_hot',$mid,60*10);//缓存有效期10分钟
        return json_encode(['code'=>10001,'msg'=>'记录成功','data'=>$hid]);
        return json_encode(['code'=>10002,'msg'=>'记录失败']);
    }

    //缘分基因检测
    public function getBothSidesFateGene()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
		if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];  
        $mid = $data['mid'];
        $re = Db::name('user')->where(array('User_id'=>$uid))->find();
    }

    private function _queryPairAllUserList($data,$redata,$sort)
    {
        foreach($redata as $r =>$e){
                $Integrity = 0;
                $Fate = 0;
                if($e['Card_portrait']){
                    $Integrity +=1;
                }
                if($e['Head_portrait']){
                    $Integrity +=1;
                }
                if($e['Username']){
                    $Integrity +=1;
                }
                if($e['Introduce']){
                    $Integrity +=1;
                }
                if($e['Card_address']){
                    $Integrity +=1;
                }
                if($e['Realname']){
                    $Integrity +=2;
                }
                if($e['Phone']){
                    $Integrity +=2;
                }
                if($e['Wechat']){
                    $Integrity +=2;
                }
                if($data['Hometowns'] && $e['Hometowns']){//同乡
                    $Integrity +=1;
                    $Hometowns1 = json_decode($data['Hometowns'],true);
                    $Hometowns2 = json_decode($e['Hometowns'],true);
                    if(is_array($Hometowns1) && is_array($Hometowns2)){
                        for($i=0;$i<count($Hometowns1);$i++){
                            for($t=0;$t<count($Hometowns2);$t++){
                                if($Hometowns1[$i]['province'] == $Hometowns2[$t]['province'] && $Hometowns1[$i]['city'] == $Hometowns2[$t]['city']){
                                    $Fate += 10;
                                    break;
                                }
                            }
                        }
                    }
                }
                if($data['Locations'] && $e['Locations']){//同城
                        $Integrity +=1;
                        $Locations1 = json_decode($data['Locations'],true);
                        $Locations2 = json_decode($e['Locations'],true);
                        if(is_array($Locations1) && is_array($Locations2)){
                            for($i=0;$i<count($Locations1);$i++){
                                for($t=0;$t<count($Locations2);$t++){                               
                                if($Locations1[$i]['province'] == $Locations2[$t]['province'] && $Locations1[$i]['city'] == $Locations2[$t]['city']){
                                    $Fate += 10;
                                    break;
                                }
                            }
                        }
                    }
                }
                if($data['Campus'] && $e['Campus']){//同校
                    $Integrity +=1;
                    $Campus1 = explode(',', $data['Campus']);
                    $Campus2 = explode(',', $e['Campus']);
                    if(is_array($Campus1) && is_array($Campus2)){                       
                        $Campus = array_intersect($Campus1,$Campus2);
                        if($Campus){
                            $Fate += 10;
                        }
                    }
                }
                if($data['Demand'] && $e['Demand']){//同需求
                    $Integrity +=1;
                    $Demand1 = explode(',', $data['Demand']);
                    $Demand2 = explode(',', $e['Demand']);
                    if(is_array($Demand1) && is_array($Demand2)){                       
                        $Demands = array_intersect($Demand1,$Demand2);
                        if($Demands){
                            $Fate += 10;
                        }
                    }
                }
                if($data['Languages'] && $e['Languages']){//同语言
                    $Integrity +=1;
                    $Languages1 = explode(',', $data['Languages']);
                    $Languages2 = explode(',', $e['Languages']);
                    if(is_array($Languages1) && is_array($Languages2)){                       
                        $Languages = array_intersect($Languages1,$Languages2);
                        if($Languages){
                            $Fate += 10;
                        }
                    }
                }
                if($data['Hobbys'] && $e['Hobbys']){//同趣
                    $Integrity +=1;
                    $Hobbys1 = explode(',', $data['Hobbys']);
                    $Hobbys2 = explode(',', $e['Hobbys']);
                    if(is_array($Hobbys1) && is_array($Hobbys2)){                       
                        $Hobbys = array_intersect($Hobbys1,$Hobbys2);
                        if($Hobbys){
                            $count = count($Hobbys);
                            if($count>5) 
                            $count = 5;
                            $Fate += 2*$count;
                            $redata[$r]['Hobby'] = $Hobbys;
                        }
                    }
                }
                if($data['Age'] && $e['Age']){//同龄
                    $Integrity +=1;
                    if($data['Age'] < $e['Age']+2 && $data['Age']>$e['Age']-2){
                        $Fate += 10;
                    }
                }
                if($data['Gender'] && $e['Gender']){//异性
                    $Integrity +=1;
                    if($data['Gender'] != $e['Gender']){
                        $Fate += 10;
                    }
                }
                if($data['Marriage'] && $e['Marriage']){//婚恋状况
                    $Integrity +=1;
                    if($data['Marriage'] == $e['Marriage']){
                        $Fate += 10;
                    }
                }
                if($data['Longitud'] && $data['Latitude'] && $e['Longitud'] && $e['Latitude']){
                    $Integrity +=1;
                    $distance = judgedistance($data['Longitud'],$data['Latitude'],$e['Longitud'],$e['Latitude']);
                    if($distance <3){
                        $Fate += 10;
                        $redata[$r]['Distance'] = $distance;
                    }
                }
                $redata[$r]['Fate'] = $Fate;
                $redata[$r]['Info_integrity'] = $Integrity;
                $redata[$r]['Giveup_volume'] = count(getUserGiveUpList($e['User_id']));
				$redata[$r]['Giveup_state'] = judgeUserGiveUpState($data['User_id'],$e['User_id']);
 				$sort = 'Fate';
        }
        $sort1 = array_column($redata,'Fate');
        $sort2 = array_column($redata,'Info_integrity');
        $sort3 = array_column($redata,'Giveup_volume');
        $sort4 = array_column($redata,'Land_time');
        array_multisort($sort1,SORT_DESC,$sort2,SORT_DESC,$sort3,SORT_DESC,$sort4,SORT_DESC,$redata);
        return $redata;
    }
}
